Page({
  data: {
    bookId: null, // 添加 bookId 到 data 中
    total: 0, // 总章节数
    currentId: 0, // 当前章节 ID
    chapter: {
      // 当前章节内容
      title: '',
      content: '',
    },
  },

  onLoad(options) {
    const bookId = options.bookId;
    const chapterId = parseInt(options.chapterId, 10); // 将章节 ID 转换为整数
    this.loadChapterContent(bookId, chapterId);
    this.setData({
      bookId: bookId, // 保存 bookId 到 data 中
      total: parseInt(options.total, 10),
      currentId: chapterId,
    });
  },

  async loadChapterContent(bookId, chapterId) {
    wx.showLoading({
      title: '加载中...',
    });

    try {
      const app = getApp();
      const chapterContent = await app.fetchData(
        `http://1.94.51.11:8849/workcontent/${bookId}/${chapterId}`
      );
      this.setData({ chapter: chapterContent, currentId: chapterId });
    } catch (error) {
      console.error('Failed to fetch chapter content', error);
    } finally {
      wx.hideLoading();
    }
  },

  goToPreChapter() {
    const { currentId, bookId } = this.data; // 从 data 中获取 bookId 和 currentId
    if (currentId > 1) {
      this.loadChapterContent(bookId, currentId - 1);
    } else {
      wx.showToast({
        title: '已经是第一章',
        icon: 'none',
      });
    }
  },

  goToNextChapter() {
    const { currentId, total, bookId } = this.data; // 从 data 中获取 bookId 和 currentId
    if (currentId < total) {
      this.loadChapterContent(bookId, currentId + 1);
    } else {
      wx.showToast({
        title: '已经是最后一章',
        icon: 'none',
      });
    }
  },
});
